Creating a CAPTCHA in PHP 8 can help protect your website from automated bots and spam attacks. CAPTCHA stands for "Completely Automated Public Turing test to tell Computers and Humans Apart." It typically presents a challenge or puzzle that humans can easily solve, but bots find difficult.
```php
session_start();
// Function to generate a random string for the CAPTCHA
function generateCaptchaText($length = 6)
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$captchaText = '';
for ($i = 0; $i < $length; $i++) {
$captchaText .= $characters[rand(0, strlen($characters) - 1)];
}
return $captchaText;
}
// Generate a random CAPTCHA text and store it in the session
$captchaText = generateCaptchaText();
$_SESSION['captcha'] = $captchaText;
// Create a blank image
$captchaImage = imagecreatetruecolor(120, 40);
// Set background color (white)
$bgColor = imagecolorallocate($captchaImage, 255, 255, 255);
imagefill($captchaImage, 0, 0, $bgColor);
// Set text color (black)
$textColor = imagecolorallocate($captchaImage, 0, 0, 0);
// Draw the text on the image
imagestring($captchaImage, 5, 30, 15, $captchaText, $textColor);
// Add some random lines to make it harder for bots to read
for ($i = 0; $i < 5; $i++) {
$lineColor = imagecolorallocate($captchaImage, rand(0, 255), rand(0, 255), rand(0, 255));
imageline($captchaImage, rand(0, 120), rand(0, 40), rand(0, 120), rand(0, 40), $lineColor);
}
// Output the image as PNG
imagepng($captchaImage);
imagedestroy($captchaImage);
?>
```
```php
```
```php
session_start();
// Get the user input
// Retrieve the stored CAPTCHA text from the session
// Compare the user input with the CAPTCHA text
if (strcasecmp($userInput, $captchaText) === 0) {
// CAPTCHA is correct - process the form or allow access
echo "CAPTCHA verification successful!";
// Additional logic or form processing can be added here
} else {
// CAPTCHA is incorrect - show an error message
echo "CAPTCHA verification failed. Please try again.";
}
?>
```
Please note that this is just a basic example, and there are more sophisticated CAPTCHA techniques available to improve security. Additionally, the use of PHP's GD extension is demonstrated here, but you can explore other libraries or tools for generating more complex CAPTCHA images. Always keep in mind that CAPTCHAs alone may not be sufficient for robust security, and other security measures should be implemented in combination with CAPTCHAs.